<template>
  <div>
    <el-form
      ref="deptForm"
      label-width="150px"
      :model="form"
      :rules="fromRules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          style="width: 80%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in employees"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import {
  addDepartments,
  getDepartDetail,
  editDepartments
} from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 校验函数 -> 部门编码在整个模块中都不允许重复
    const vaildCode = (rule, value, callback) => {
      // 筛选出originList中所有code
      let exiseCodeList = this.originList.map((item) => item.code)
      // 非重验证 -> 过滤掉当前的部门, map得到部门编号列表
      exiseCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      // includes方法判断是否在数组中
      exiseCodeList.includes(value)
        ? callback(new Error('编码' + value + '已存在'))
        : callback()
    }
    // 校验函数 -> 部门名字在同级部门中不允许重复
    const vaildName = (rule, value, callback) => {
      // 在某个部门上点击添加子部门 表单中部门名字不能与他的子部门名字相同
      let exiseNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // 如果是编辑 则被占用的名字 = 兄弟-自己
      if (this.isEdit) {
        const dept = this.originList.find(item => item.id === this.id) // 得到当前部门对象
        const pid = dept.pid // 得到父级的id -> 取出pid
        exiseNameList = this.originList.filter(item => item.pid === pid && item.id !== this.id) // 所有的兄弟 && 不包括自己
          .map(item => item.name) // 只需要name属性
      }
      console.log('被占用的name:', exiseNameList)
      exiseNameList.includes(value) ? callback(new Error('名字' + value + '在同级部门中已存在')) : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employees: [], // 存储员工简单列表
      fromRules: {
        name: [
          { required: true, message: '部门名称不能为欧空', trigger: 'blur' },
          { validator: vaildName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门名称不能为欧空', trigger: 'blur' },
          { validator: vaildCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门名称不能为欧空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          }
        ],
        introduce: [
          { required: true, message: '部门名称不能为欧空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.loadEmployee()
    if (this.isEdit) {
      this.loadDepartmentsDetail() // 如果是编辑框 自动渲染表单
    }
  },
  methods: {
    // 确定 -> 兜底校验
    hSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消
    hCancel() {
      this.$emit('success')
    },
    // 请求员工简单列表
    async loadEmployee() {
      const res = await getEmployeeSimple()
      console.log('员工简单列表', res)
      this.employees = res.data
    },
    // 添加部门
    async doAdd() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log('添加部门', res)
        // 添加成功
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 请求部门详细信息 渲染到表单
    async loadDepartmentsDetail() {
      try {
        if (this.isEdit) {
          const res = await getDepartDetail(this.id)
          console.log('请求部门详细信息', res)
          this.form = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑部门
    async doEdit() {
      try {
        const res = await editDepartments({ id: this.id, ...this.form })
        console.log('修改部门', res)
        // 修改成功
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 清空表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>

<style></style>
